package com.manli.api.service;

import com.manli.api.dao.MajorBranchPartnerDao;
import com.manli.api.dto.MajorBranchPartner;
import com.manli.api.pojo.LocationPoint;
import com.manli.api.pojo.QueryParamsPartner;
import com.manli.api.util.*;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Set;

import com.manli.api.pojo.Result;
import com.manli.api.pojo.SessionInfo;

import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import com.manli.api.dao.PartnerDao;
import com.manli.api.dto.Branch;
import com.manli.api.dto.Partner;
import org.springframework.transaction.annotation.Transactional;


@Service("partnerService")
public class PartnerService {
    @Autowired
    PartnerDao partnerDao;
    @Autowired
    SessionInfoUtils sessionInfoUtils;
    @Autowired
    SQLManager sqlManager;
    @Autowired
    MajorBranchPartnerDao majorBranchPartnerDao;
    
    public Result queryPage(QueryParamsPartner params,HttpServletRequest request) {
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

        StringBuffer sql = new StringBuffer("SELECT a.*,b.branch_name FROM partner a left join branch b on a.branch_id = b.branch_id where 1=1 ");

        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getPartnerName())?"":" and a.partner_name like '%" + params.getPartnerName() + "%'");
        sql.append(params.getStatus() == null?" ":" and a.status = " + params.getStatus()+" " );
        if(sessionInfo.getBranchId() == 1){
            sql.append(sessionInfo.getBranchId() == 1?"":" and a.branch_id = " + sessionInfo.getBranchId() +" " );
        }else{
            sql.append((params.getBranchId() == null)?" and a.branch_id = " + sessionInfo.getBranchId() +" ":" and branch_id =" + params.getBranchId() + " ");
        }

        sql.append(" order by a.status desc , a.partner_id desc  ");

        SQLReady sqlReady = new SQLReady(sql.toString());

        PageQuery<Partner> pageQuery = new PageQuery<Partner>(params.getPage(),params.getLimit());
        PageQuery<Partner> query =sqlManager.execute(sqlReady,Partner.class,pageQuery);


        //查询分店下的多个主营类别
        query.getList().forEach(partner -> {
            String sql1 = "select a.major_type_id from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.branch_id = " + partner.getBranchId() +" and a.partner_id = " + partner.getPartnerId();
            SQLReady sqlReady1 = new SQLReady(sql1);
            List<Integer> list = sqlManager.execute(sqlReady1,Integer.class);
            partner.setMajorTypeId(list);

            String sql2 = "select GROUP_CONCAT(b.major_name) major_name from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.branch_id = " + partner.getBranchId() +" and  a.partner_id = " +partner.getPartnerId();
            SQLReady sqlReady2 = new SQLReady(sql2);
            List<String> list1 = sqlManager.execute(sqlReady2,String.class);
            partner.setMajorName(list1.size()>0?list1.get(0):"");
        });

        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    
    public Result queryAll(QueryParamsPartner params,HttpServletRequest request) {
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        StringBuffer sql = new StringBuffer("SELECT " +
                " a.* " +
                "FROM " +
                " partner a " +
                " where 1=1 ");


        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getPartnerName())?"":" and a.partner_name like '%" + params.getPartnerName() + "%'");
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getStatus())?"":" and a.status = " + params.getStatus()+" " );
        if(sessionInfo.getBranchId() == 1){
            sql.append(sessionInfo.getBranchId() == 1?"":" and a.branch_id = " + sessionInfo.getBranchId() +" " );
        }else{
            sql.append((params.getBranchId() == null)?"":" and branch_id =" + params.getBranchId() + " ");
        }
        sql.append(" order by a.status desc , a.partner_id desc  ");

        SQLReady sqlReady = new SQLReady(sql.toString());

        List<Partner> query =sqlManager.execute(sqlReady,Partner.class);

        //查询分店下的多个主营类别
        query.forEach(partner -> {
            String sql1 = "select a.major_type_id from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.branch_id = " + partner.getBranchId() +" and a.partner_id = " + partner.getPartnerId();
            SQLReady sqlReady1 = new SQLReady(sql1);
            List<Integer> list = sqlManager.execute(sqlReady1,Integer.class);
            partner.setMajorTypeId(list);

            String sql2 = "select GROUP_CONCAT(b.major_name) major_name from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.branch_id = " + partner.getBranchId() +" and  a.partner_id = " +partner.getPartnerId();
            SQLReady sqlReady2 = new SQLReady(sql2);
            List<String> list1 = sqlManager.execute(sqlReady2,String.class);
            partner.setMajorName(list1.size()>0?list1.get(0):"");
        });

        return ResultUtil.success(query);
    }

    public Result queryAll1(QueryParamsPartner params,HttpServletRequest request) {
        StringBuffer sql = new StringBuffer("SELECT " +
                " a.* " +
                "FROM " +
                " partner a " +
                " where 1=1 ");

        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getPartnerName())?"":" and a.partner_name like '%" + params.getPartnerName() + "%'");
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getStatus())?"":" and a.status = " + params.getStatus()+" " );
        sql.append((params.getBranchId() == null)?"":" and a.branch_id =" + params.getBranchId() + " ");
        sql.append(" order by a.status desc , a.partner_id desc  ");

        SQLReady sqlReady = new SQLReady(sql.toString());

        List<Partner> query =sqlManager.execute(sqlReady,Partner.class);

        //查询分店下的多个主营类别
        query.forEach(partner -> {
            String sql1 = "select a.major_type_id from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.branch_id = " + partner.getBranchId() +" and a.partner_id = " + partner.getPartnerId();
            SQLReady sqlReady1 = new SQLReady(sql1);
            List<Integer> list = sqlManager.execute(sqlReady1,Integer.class);
            partner.setMajorTypeId(list);

            String sql2 = "select GROUP_CONCAT(b.major_name) major_name from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.branch_id = " + partner.getBranchId() +" and  a.partner_id = " +partner.getPartnerId();
            SQLReady sqlReady2 = new SQLReady(sql2);
            List<String> list1 = sqlManager.execute(sqlReady2,String.class);
            partner.setMajorName(list1.size()>0?list1.get(0):"");
        });

        return ResultUtil.success(query);
    }

    
    public Result getById(Integer partnerId) {
        Partner partner = partnerDao.single(partnerId);
        return ResultUtil.success(partner);
    }

    @Transactional
    public Result save(Partner partner , SessionInfo sessionInfo) {
        //判断值为空
        ObjectEmptyUtil.partnerIsEmpty(partner);

        //判断partner名称是否重复
        List<Partner> list = partnerDao.execute("select * from partner where partner_name = ? and branch_id = ?",partner.getPartnerName(),partner.getBranchId());
        if(list.size() > 0){
            return ResultUtil.error(-1,"分店名称重复");
        }

        if(partner.getBranchId() == null){
            partner.setBranchId(sessionInfo.getBranchId());
        }

        LocationPoint point = new LocationPoint(Double.valueOf(partner.getLongitude()),Double.valueOf(partner.getLatitude()));
        partner.setLongitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLongitude().toString());
        partner.setLatitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLatitude().toString());
        Object id = partnerDao.insertReturnKey(partner).getKey();
        //主营类别表操作
        if(partner.getMajorTypeId().size() == 0){
            return ResultUtil.error(-1,"请选择主营类别");
        }

        partner.getMajorTypeId().forEach(majorid -> {
            MajorBranchPartner majorBranchPartner = new MajorBranchPartner();
            majorBranchPartner.setBranchId(partner.getBranchId());
            majorBranchPartner.setPartnerId(Integer.parseInt(id.toString()));
            majorBranchPartner.setMajorTypeId(majorid);
            majorBranchPartnerDao.insert(majorBranchPartner);
        });

        return ResultUtil.success();
    }

    @Transactional
    public Result updateById(Partner partner) {
        //判断值为空
        ObjectEmptyUtil.partnerIsEmpty(partner);


        //判断partner名称是否重复
        List<Partner> list = partnerDao.execute("select * from partner where partner_name = ? and partner_id != ? and branch_id = ?",partner.getPartnerName(),partner.getPartnerId(),partner.getBranchId());
        if(list.size() > 0){
            return ResultUtil.error(-1,"分店名称重复");
        }
        LocationPoint point = new LocationPoint(Double.valueOf(partner.getLongitude()),Double.valueOf(partner.getLatitude()));
        partner.setLongitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLongitude().toString());
        partner.setLatitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLatitude().toString());
        partnerDao.updateTemplateById(partner);
        //主营类别表操作
        if(partner.getMajorTypeId().size() == 0){
            return ResultUtil.error(-1,"请选择主营类别");
        }

        partnerDao.executeUpdate("delete from major_branch_partner where branch_id = ? and partner_id = ?",partner.getBranchId(),partner.getPartnerId());

        Set<Integer> majorTypeids = new HashSet<>();
        majorTypeids.addAll(partner.getMajorTypeId());
        majorTypeids.forEach(majorid -> {
            MajorBranchPartner majorBranchPartner = new MajorBranchPartner();
            majorBranchPartner.setBranchId(partner.getBranchId());
            majorBranchPartner.setPartnerId(partner.getPartnerId());
            majorBranchPartner.setMajorTypeId(majorid);
            majorBranchPartnerDao.insert(majorBranchPartner);
        });

        return ResultUtil.success();
    }

    @Transactional
    public Result removeById(Integer partnerId) {
        partnerDao.deleteById(partnerId);
        return ResultUtil.success();
    }

    @Transactional
    public Result removeByIds(List<Integer> ids) {
        for (Integer id:ids) {
            partnerDao.deleteById(id);
        }
        return ResultUtil.success();
    }

}
